package com.bc.bcapi.service;

import com.bc.bcapi.dao.T_Erc_contractMapper;
import com.bc.bcapi.dao.T_ProjectMapper;
import com.bc.bcapi.dao.T_User_walletMapper;
import com.bc.bcapi.utils.web3j.Decomposition;
import com.bc.bcapi.utils.web3j.GasService;
import com.bc.bcapi.utils.web3j.Util;
import com.bc.bccore.webconfig.WebConfig;
import com.bc.bccore.zbconfig.ZbConfig;
import com.bc.bcmodel.domain.T_Erc_contractModel;
import com.bc.bcmodel.domain.T_ProjectModel;
import com.bc.bcmodel.domain.T_User_walletModel;
import com.bc.bcmodel.req.AccountDryWithDrawReq;
import com.bc.bcmodel.resp.DepositAddress;
import com.bc.commoncore.util.HttpUtil;
import com.bc.commoncore.util.JsonUtil;
import com.bc.commonentity.common.JsonResult;
import com.bc.commonentity.enums.HttpReturnRnums;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.math.BigInteger;

import com.bc.bcapi.dao.T_Wallet_infoMapper;
import com.bc.bcmodel.domain.T_Wallet_infoModel;

/**
 * @Name T_Wallet_infoService * @Description TODO * @Author generation * @Date 2018/8/14 15:26:25 * @Version 1.0
 **/
@Service
public class T_Wallet_infoService {
    @Resource
    T_Wallet_infoMapper t_Wallet_infoMapper;
    @Resource
    T_ProjectMapper t_Project_Mapper;
    @Resource
    T_Erc_contractMapper t_erc_contractMapper;
    @Resource
    T_User_walletMapper t_user_walletMapper;

    /**
     * 保存单条数据     *      * @return
     */

    public int insert(T_Wallet_infoModel req) {
        return t_Wallet_infoMapper.insert(req);
    }

    /**
     * 批量增加数据     *      * @return
     */

    public int insertBatch(List<T_Wallet_infoModel> req) {
        return t_Wallet_infoMapper.insertBatch(req);
    }

    /**
     * 根据对象属性查找满足条件的第一条数据     *      * @return
     */

    public T_Wallet_infoModel findByNamedParam(T_Wallet_infoModel req) {
        return t_Wallet_infoMapper.findByNamedParam(req);
    }

    /**
     * 根据对象查询所有数据     *      * @return
     */

    public List<T_Wallet_infoModel> getAllList(T_Wallet_infoModel req) {
        return t_Wallet_infoMapper.findByNamedParamList(req);
    }

    /**
     * 根据对象查询所有分页数据     *      * @return
     */

    public PageInfo<T_Wallet_infoModel> getList(T_Wallet_infoModel req) {
        PageHelper.startPage(req.getPage_index(), req.getPage_size());
        List<T_Wallet_infoModel> list = t_Wallet_infoMapper.findByNamedParamList(req);
        return new PageInfo<T_Wallet_infoModel>(list);
    }

    /**
     * 更新指定对象     *      * @return
     */

    public int update(T_Wallet_infoModel req) {
        return t_Wallet_infoMapper.update(req);
    }

    /**
     * 删除指定数据     *      * @return
     */

    public int delete(BigInteger id) {
        return t_Wallet_infoMapper.delete(id);
    }

    /**
     * 根据条件统计数据量     *      * @return
     */

    public long count(T_Wallet_infoModel req) {
        return t_Wallet_infoMapper.count(req);
    }

    //处理卖家的钱包
    public List<T_Wallet_infoModel> sellerToken(String uid) {

        List<T_Wallet_infoModel> wallet_infos = new ArrayList<>();

        //获取用户的所有钱包
        T_Wallet_infoModel t_wallet_infoModel = new T_Wallet_infoModel();
        t_wallet_infoModel.setUser_id(uid);
        List<T_Wallet_infoModel> wallet_infoModels = getAllList(t_wallet_infoModel);

        String project_token;
        //获取卖家的project
        T_ProjectModel t_projectModel = new T_ProjectModel();
        t_projectModel.setUser_id(uid);
        t_projectModel = t_Project_Mapper.findByNamedParam(t_projectModel);

        if (t_projectModel != null) {
            project_token = t_projectModel.getIco_name();
        }

        //seller售出总数现在的表不好算，只能从流水表sum

        //TODO
        return wallet_infos;
    }

    public JsonResult dryWithdraw(AccountDryWithDrawReq req, String uid) throws Exception {
        String contract_id = req.getContract_id();
        T_Erc_contractModel t_erc_contractModel = new T_Erc_contractModel();
        t_erc_contractModel.setContract_id(contract_id);
        t_erc_contractModel = t_erc_contractMapper.findByNamedParam(t_erc_contractModel);

        if (t_erc_contractModel == null) {
            return new JsonResult(HttpReturnRnums.ParaError);
        }
        if (req.getValue().compareTo(BigDecimal.ZERO) < 0) {
            return new JsonResult(HttpReturnRnums.ParaError);
        }

        int decimal = 0;
        int indexof = req.getValue().toString().indexOf(".");
        if (indexof > 0) {
            decimal = req.getValue().toString().length() - 1 - indexof;
        }

        if (decimal > t_erc_contractModel.getDigit()) {
            return new JsonResult(HttpReturnRnums.ParaError);
        }

        //select wallet info
        T_Wallet_infoModel t_wallet_infoModel = new T_Wallet_infoModel();
        t_wallet_infoModel.setContract_id(contract_id);
        t_wallet_infoModel.setUser_id(uid);
        t_wallet_infoModel.setStatus("1");

        t_wallet_infoModel = t_Wallet_infoMapper.findByNamedParam(t_wallet_infoModel);

        if (t_wallet_infoModel == null) {
            return new JsonResult(HttpReturnRnums.ParaError);
        }

        //count gas
        Decomposition decomposition = GasService.getInstance()
                .setContractModel(t_erc_contractModel)
                .withdraw(req.getValue())
                .decomposit();

        if (decomposition.getActual_receipt_value().compareTo(BigDecimal.ZERO) < 0)
            decomposition.setActual_receipt_value(BigDecimal.ZERO);

        //result
        return new JsonResult(decomposition);
    }

    /**
     * 审核项目时创建ETH钱包
     */
    public void writeWalletETH(String pid) {
        T_User_walletModel t_user_walletModel = t_Wallet_infoMapper.getWalletByPid(pid);
        if (t_user_walletModel == null) {
            return;
        }
        T_Wallet_infoModel t_wallet_infoModel = new T_Wallet_infoModel();
        t_wallet_infoModel.setUser_id(t_user_walletModel.getUser_id());
        t_wallet_infoModel.setWallet_address(t_user_walletModel.getWallet_address());

        if (t_Wallet_infoMapper.count(t_wallet_infoModel) > 0) {
            return;
        }
        t_wallet_infoModel.setContract_id(Util.getETHID());
        t_wallet_infoModel.setStatus("1");
        t_Wallet_infoMapper.insert(t_wallet_infoModel);
    }

    /**
     * 审核项目时创建Eos钱包
     */
    public void writeWalletEos(String pid) {
        T_User_walletModel t_user_walletModel = t_Wallet_infoMapper.getWalletByPid(pid);
        if (t_user_walletModel == null) {
            return;
        }
        T_Wallet_infoModel t_wallet_infoModel = new T_Wallet_infoModel();
        t_wallet_infoModel.setUser_id(t_user_walletModel.getUser_id());

        /*这里去获取eos的接口*/
        String userId = t_user_walletModel.getWallet_address();
        String addressStr = HttpUtil.sendGet(ZbConfig.getEosUrl() + "eos/deposit/address?userId=" + userId, "");
        DepositAddress depositAddress = JsonUtil.str2obj(addressStr, DepositAddress.class);
        if (depositAddress == null) {
            return;
        }
        t_wallet_infoModel.setWallet_address(depositAddress.getMemo().toString());

        if (t_Wallet_infoMapper.count(t_wallet_infoModel) > 0) {
            return;
        }
        t_wallet_infoModel.setContract_id(Util.getEOS());
        t_wallet_infoModel.setStatus("1");
        t_Wallet_infoMapper.insert(t_wallet_infoModel);
    }
}